using System;
using System.Collections;
using System.Web;
using log4net;

namespace Sedna.Core.Controller
{
	/// <summary>
	/// Default implementation for ISessionWrapper.
	/// </summary>

	public class CurrentContextSessionWrapper: ISessionWrapper
	{
		private ILog log=LogManager.GetLogger(typeof(CurrentContextSessionWrapper));

		public CurrentContextSessionWrapper()
		{

		}
		

		public object this[object index]
		{
			get
			{
				if (CurrentSessionState==null)
				{
					return null;
				}
				return CurrentSessionState[index];
			}
			set
			{
				if (CurrentSessionState!=null)
				{
					CurrentSessionState[index]=value;
					return;
				}
				IDictionary sessionState=new Hashtable();
				sessionState[index]=value;
				CurrentSessionState=sessionState;
			}
		}

		public void Clear()
		{
			CurrentSessionState=null;
		}

		public void Remove(object key)
		{
			if (CurrentSessionState==null)
			{
				return;
			}
			CurrentSessionState.Remove(key);
		}



		private IDictionary CurrentSessionState
		{
			get {return GetCurrentSessionState();}
			set {SetCurrentSessionState(value);}
		}

		private string SessionKey
		{
			get
			{
				return (string)Context.Items["infrastructure.SessionKey"];
			}
		}

		private HttpContext Context
		{
			get {return HttpContext.Current;}
		}

		private IDictionary GetCurrentSessionState()
		{
			if (SessionKey==null||SessionKey.Trim().Equals(String.Empty))
			{
				return null;
			}

			return (IDictionary)Context.Session[SessionKey];
			 
		}

		private void SetCurrentSessionState(IDictionary sessionState)
		{
			if (SessionKey==null)
			{
				if (log.IsDebugEnabled)
				{
					log.Debug("Cannot set session value. Cannot determine SessionKey. Probably, current page doesn't derive from BasePage.");
				}
				return;
			}

			if (sessionState==null)
			{
				Context.Session.Remove(SessionKey);	
				return;
			}

			Context.Session[SessionKey]=sessionState;
		}
	}
}
